package com.qf.wangqing.sportsnews.adapter.headline;

import android.content.Context;
import android.databinding.DataBindingUtil;
import android.databinding.ViewDataBinding;
import android.support.v7.widget.RecyclerView;
import android.util.Pair;
import android.view.LayoutInflater;
import android.view.ViewGroup;

import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by ShenHao on 2016/12/16.
 */

public class AdapterRecHead<D> extends RecyclerView.Adapter<AdapterRecHead.MyViewHolder> {


    private Context context;
    private Map<Class<?>, Pair<Integer, Integer>> map;
    private List<D> list;
    public AdapterRecHead(List<D> list, Context context, int layoutId, int variableId) {
        this.list = list;
        this.context = context;
        map = new HashMap<>();
        map.put(null, Pair.create(layoutId, variableId));
    }

    public AdapterRecHead(Context context, Map<Class<?>, Pair<Integer, Integer>> map, List<D> list) {
        this.context = context;
        this.map = map;
        this.list = list;
    }

    @Override
    public int getItemViewType(int position) {
        if (map.size() == 1) {
            return map.get(null).first;
        } else {
            return map.get(list.get(position)).first;
        }
    }

    @Override
    public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        return new MyViewHolder(DataBindingUtil.inflate(LayoutInflater.from(context), viewType, parent, false));
    }

    @Override
    public void onBindViewHolder(MyViewHolder holder, int position) {
        D d = list.get(position);
        Pair<Integer,Integer>pair;
        if (map.size()==1){
            pair=map.get(null);
        }else{
            pair=map.get(d.getClass());
        }
        holder.binding.setVariable(pair.second, d);
    }

    @Override
    public int getItemCount() {
        return list.size();
    }

    public void add(D d) {
        add(list.size(), d);
    }

    public void add(int position, D d) {
        list.add(position, d);
        notifyItemInserted(position);
    }

    public void addAll(Collection<? extends D> collection) {
        addAll(list.size(), collection);
    }

    public void addAll(int position, Collection<? extends D> collection) {
        list.addAll(position, collection);
        notifyItemRangeInserted(position, list.size());
    }


    public void remove(D d) {
        int indexOf = list.indexOf(d);
        remove(indexOf);
    }

    public void remove(int position) {
        list.remove(position);
        notifyItemRemoved(position);
    }


    public static class MyViewHolder extends RecyclerView.ViewHolder {
        private ViewDataBinding binding;

        public MyViewHolder(ViewDataBinding binding) {
            super(binding.getRoot());
            this.binding = binding;
        }
    }
}
